<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button onclick="login()">POST /login</button>
    <button onclick="getPosts()">GET /posts</button>
    <button onclick="getPostsById(2)">GET /posts/:id</button>

    <button onclick="addPostsJSON()">(JOSN) POST /posts</button>
    <button onclick="updatePostsById(2)">(JOSN) PATCH /posts/:id</button>
    <button onclick="deletePostsById(2)">DELETE /posts/:id</button>

    <script src="./axios.js"></script>
    <script>
      /*
        axios对象方法参数：
        1. url 路由地址
        2. 报文主体 GET,DELETE请求可以省略
        3. 配置项
          ① params 配置查询参数
          ② headers 配置报文头部字段
      */
      let token = ""; //保存令牌

      function login() {
        axios
          .post("http://127.0.0.1:3008/login", {
            username: "jack",
            password: "123123",
          })
          .then((res) => {
            token = res.data.data;
          })
          .catch((err) => {
            console.log(err);
          });
      }
      // query string查询字符串传参
      function getPosts() {
        axios
          .get("http://127.0.0.1:3008/posts", {
            params: { id_gte: 2, id_lte: 5 },
            headers: { authorization: token },
          })
          .then((res) => {
            console.log(res);
          })
          .catch((e) => {
            console.log(e);
          });
      }
      // path 路径传参
      function getPostsById(id) {
        axios
          .get(`http://127.0.0.1:3008/posts/${id}`, {
            headers: { authorization: token },
          })
          .then((res) => {
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
          });
      }
      // 报文主体（JOSN）传参
      function addPostsJSON() {
        axios
          .post(
            "http://127.0.0.1:3008/posts",
            {
              author: "tom",
              title: "hello tome",
            },
            {
              headers: { authorization: token },
            }
          )
          .then((res) => console.log(res))
          .catch((err) => console.log(err));
      }
      // path 路径传参+报文主体（JOSN）传参
      function updatePostsById(id) {
        axios
          .patch(
            `http://127.0.0.1:3008/posts/${id}`,
            {
              title: "hahaha ...",
            },
            {
              headers: { authorization: token },
            }
          )
          .then((res) => console.log(res))
          .catch((err) => console.log(err));
      }
      // path 路径传参
      function deletePostsById(id) {
        axios
          .delete(`http://127.0.0.1:3008/posts/${id}`, {
            headers: { authorization: token },
          })
          .then((res) => console.log(res))
          .catch((err) => console.log(err));
      }
    </script>
  </body>
</html>
